<template>
  <div class="family-stats">
    <div class="stats-header">
      <h3>家族统计</h3>
      <div class="refresh-btn" @click="refreshStats">
        <span>🔄</span>
      </div>
    </div>
    
    <div class="stats-grid">
      <!-- 基础统计 -->
      <div class="stat-card">
        <div class="stat-icon">👥</div>
        <div class="stat-content">
          <div class="stat-number">{{ totalMembers }}</div>
          <div class="stat-label">总成员数</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon">🏠</div>
        <div class="stat-content">
          <div class="stat-number">{{ generations.length }}</div>
          <div class="stat-label">世代数</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon">💑</div>
        <div class="stat-content">
          <div class="stat-number">{{ marriedCount }}</div>
          <div class="stat-label">已婚成员</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon">👶</div>
        <div class="stat-content">
          <div class="stat-number">{{ childrenCount }}</div>
          <div class="stat-label">子女总数</div>
        </div>
      </div>
    </div>
    
    <!-- 性别分布 -->
    <div class="stats-section">
      <h4>性别分布</h4>
      <div class="gender-stats">
        <div class="gender-item male">
          <div class="gender-icon">👨</div>
          <div class="gender-info">
            <div class="gender-number">{{ maleCount }}</div>
            <div class="gender-percentage">{{ malePercentage }}%</div>
          </div>
        </div>
        <div class="gender-item female">
          <div class="gender-icon">👩</div>
          <div class="gender-info">
            <div class="gender-number">{{ femaleCount }}</div>
            <div class="gender-percentage">{{ femalePercentage }}%</div>
          </div>
        </div>
      </div>
      <div class="gender-chart">
        <div class="gender-bar">
          <div class="male-bar" :style="{ width: malePercentage + '%' }"></div>
          <div class="female-bar" :style="{ width: femalePercentage + '%' }"></div>
        </div>
      </div>
    </div>
    
    <!-- 世代分布 -->
    <div class="stats-section">
      <h4>世代分布</h4>
      <div class="generation-stats">
        <div 
          v-for="gen in generations" 
          :key="gen.generation" 
          class="generation-item"
        >
          <div class="generation-label">{{ gen.generation }}代</div>
          <div class="generation-bar-container">
            <div 
              class="generation-bar" 
              :style="{ width: gen.percentage + '%' }"
            ></div>
            <span class="generation-count">{{ gen.count }}人</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 年龄分布 -->
    <div class="stats-section">
      <h4>年龄分布</h4>
      <div class="age-stats">
        <div class="age-group" v-for="group in ageGroups" :key="group.range">
          <div class="age-label">{{ group.range }}</div>
          <div class="age-bar-container">
            <div 
              class="age-bar" 
              :style="{ width: group.percentage + '%' }"
            ></div>
            <span class="age-count">{{ group.count }}人</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 关系类型分布 -->
    <div class="stats-section">
      <h4>关系类型分布</h4>
      <div class="relationship-stats">
        <div 
          v-for="rel in relationshipTypes" 
          :key="rel.type" 
          class="relationship-item"
        >
          <div class="relationship-label">{{ rel.label }}</div>
          <div class="relationship-bar-container">
            <div 
              class="relationship-bar" 
              :style="{ width: rel.percentage + '%' }"
            ></div>
            <span class="relationship-count">{{ rel.count }}人</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 教育程度分布 -->
    <div class="stats-section">
      <h4>教育程度分布</h4>
      <div class="education-stats">
        <div 
          v-for="edu in educationLevels" 
          :key="edu.level" 
          class="education-item"
        >
          <div class="education-label">{{ edu.label }}</div>
          <div class="education-bar-container">
            <div 
              class="education-bar" 
              :style="{ width: edu.percentage + '%' }"
            ></div>
            <span class="education-count">{{ edu.count }}人</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 婚姻状态分布 -->
    <div class="stats-section">
      <h4>婚姻状态分布</h4>
      <div class="marital-stats">
        <div 
          v-for="status in maritalStatuses" 
          :key="status.status" 
          class="marital-item"
        >
          <div class="marital-label">{{ status.label }}</div>
          <div class="marital-bar-container">
            <div 
              class="marital-bar" 
              :style="{ width: status.percentage + '%' }"
            ></div>
            <span class="marital-count">{{ status.count }}人</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 最新动态 -->
    <div class="stats-section">
      <h4>最新动态</h4>
      <div class="recent-activities">
        <div 
          v-for="activity in recentActivities" 
          :key="activity.id" 
          class="activity-item"
        >
          <div class="activity-icon">{{ activity.icon }}</div>
          <div class="activity-content">
            <div class="activity-text">{{ activity.text }}</div>
            <div class="activity-time">{{ activity.time }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';

export default {
  name: 'FamilyStats',
  props: {
    members: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    // 基础统计
    const totalMembers = computed(() => props.members.length);
    
    const maleCount = computed(() => 
      props.members.filter(m => m.gender === '男').length
    );
    
    const femaleCount = computed(() => 
      props.members.filter(m => m.gender === '女').length
    );
    
    const malePercentage = computed(() => 
      totalMembers.value > 0 ? Math.round((maleCount.value / totalMembers.value) * 100) : 0
    );
    
    const femalePercentage = computed(() => 
      totalMembers.value > 0 ? Math.round((femaleCount.value / totalMembers.value) * 100) : 0
    );
    
    const marriedCount = computed(() => 
      props.members.filter(m => m.maritalStatus === '已婚').length
    );
    
    const childrenCount = computed(() => 
      props.members.filter(m => m.fatherId || m.motherId).length
    );
    
    // 世代分布
    const generations = computed(() => {
      const genMap = new Map();
      
      props.members.forEach(member => {
        const gen = member.generation || 1;
        genMap.set(gen, (genMap.get(gen) || 0) + 1);
      });
      
      return Array.from(genMap.entries())
        .sort(([a], [b]) => a - b)
        .map(([generation, count]) => ({
          generation,
          count,
          percentage: totalMembers.value > 0 ? Math.round((count / totalMembers.value) * 100) : 0
        }));
    });
    
    // 年龄分布
    const ageGroups = computed(() => {
      const groups = [
        { range: '0-18岁', min: 0, max: 18, count: 0 },
        { range: '19-30岁', min: 19, max: 30, count: 0 },
        { range: '31-50岁', min: 31, max: 50, count: 0 },
        { range: '51-70岁', min: 51, max: 70, count: 0 },
        { range: '70岁以上', min: 71, max: 999, count: 0 }
      ];
      
      const currentYear = new Date().getFullYear();
      
      props.members.forEach(member => {
        if (member.birthDate) {
          const birthYear = new Date(member.birthDate).getFullYear();
          const age = currentYear - birthYear;
          
          const group = groups.find(g => age >= g.min && age <= g.max);
          if (group) {
            group.count++;
          }
        }
      });
      
      return groups.map(group => ({
        ...group,
        percentage: totalMembers.value > 0 ? Math.round((group.count / totalMembers.value) * 100) : 0
      }));
    });
    
    // 关系类型分布
    const relationshipTypes = computed(() => {
      const types = [
        { type: '亲生', label: '亲生子女', count: 0 },
        { type: '继子', label: '继子女', count: 0 },
        { type: '养子', label: '养子女', count: 0 },
        { type: '过继', label: '过继子女', count: 0 },
        { type: '其他', label: '其他关系', count: 0 }
      ];
      
      props.members.forEach(member => {
        const type = types.find(t => t.type === member.relationshipType);
        if (type) {
          type.count++;
        }
      });
      
      return types.map(type => ({
        ...type,
        percentage: totalMembers.value > 0 ? Math.round((type.count / totalMembers.value) * 100) : 0
      }));
    });
    
    // 教育程度分布
    const educationLevels = computed(() => {
      const levels = [
        { level: '小学', label: '小学', count: 0 },
        { level: '初中', label: '初中', count: 0 },
        { level: '高中', label: '高中', count: 0 },
        { level: '大专', label: '大专', count: 0 },
        { level: '本科', label: '本科', count: 0 },
        { level: '硕士', label: '硕士', count: 0 },
        { level: '博士', label: '博士', count: 0 },
        { level: '其他', label: '其他', count: 0 }
      ];
      
      props.members.forEach(member => {
        if (member.education) {
          const level = levels.find(l => l.level === member.education);
          if (level) {
            level.count++;
          }
        }
      });
      
      return levels.filter(level => level.count > 0).map(level => ({
        ...level,
        percentage: totalMembers.value > 0 ? Math.round((level.count / totalMembers.value) * 100) : 0
      }));
    });
    
    // 婚姻状态分布
    const maritalStatuses = computed(() => {
      const statuses = [
        { status: '未婚', label: '未婚', count: 0 },
        { status: '已婚', label: '已婚', count: 0 },
        { status: '离异', label: '离异', count: 0 },
        { status: '丧偶', label: '丧偶', count: 0 },
        { status: '再婚', label: '再婚', count: 0 }
      ];
      
      props.members.forEach(member => {
        if (member.maritalStatus) {
          const status = statuses.find(s => s.status === member.maritalStatus);
          if (status) {
            status.count++;
          }
        }
      });
      
      return statuses.filter(status => status.count > 0).map(status => ({
        ...status,
        percentage: totalMembers.value > 0 ? Math.round((status.count / totalMembers.value) * 100) : 0
      }));
    });
    
    // 最新动态
    const recentActivities = computed(() => {
      const activities = [];
      const currentDate = new Date();
      
      // 最近添加的成员
      const recentMembers = props.members
        .filter(m => m.createdAt)
        .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
        .slice(0, 3);
      
      recentMembers.forEach(member => {
        const daysAgo = Math.floor((currentDate - new Date(member.createdAt)) / (1000 * 60 * 60 * 24));
        activities.push({
          id: `member-${member.id}`,
          icon: '👤',
          text: `添加了新成员：${member.name}`,
          time: daysAgo === 0 ? '今天' : `${daysAgo}天前`
        });
      });
      
      // 最近更新的成员
      const updatedMembers = props.members
        .filter(m => m.updatedAt && m.updatedAt !== m.createdAt)
        .sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
        .slice(0, 2);
      
      updatedMembers.forEach(member => {
        const daysAgo = Math.floor((currentDate - new Date(member.updatedAt)) / (1000 * 60 * 60 * 24));
        activities.push({
          id: `update-${member.id}`,
          icon: '✏️',
          text: `更新了成员信息：${member.name}`,
          time: daysAgo === 0 ? '今天' : `${daysAgo}天前`
        });
      });
      
      return activities.sort((a, b) => {
        const aTime = a.time.includes('今天') ? 0 : parseInt(a.time);
        const bTime = b.time.includes('今天') ? 0 : parseInt(b.time);
        return aTime - bTime;
      }).slice(0, 5);
    });
    
    // 刷新统计
    const refreshStats = () => {
      // 触发重新计算
    };
    
    return {
      totalMembers,
      maleCount,
      femaleCount,
      malePercentage,
      femalePercentage,
      marriedCount,
      childrenCount,
      generations,
      ageGroups,
      relationshipTypes,
      educationLevels,
      maritalStatuses,
      recentActivities,
      refreshStats
    };
  }
};
</script>

<style scoped>
.family-stats {
  padding: 20px;
  background-color: #f8f9fa;
  height: 100%;
  overflow-y: auto;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.stats-header h3 {
  margin: 0;
  color: #333;
}

.refresh-btn {
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  background-color: white;
  border: 1px solid #ddd;
  transition: background-color 0.3s;
}

.refresh-btn:hover {
  background-color: #f0f0f0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 30px;
}

.stat-card {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  font-size: 24px;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #e3f2fd;
  border-radius: 50%;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.stats-section {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stats-section h4 {
  margin: 0 0 15px 0;
  color: #333;
  border-bottom: 2px solid #4CAF50;
  padding-bottom: 5px;
}

/* 性别分布 */
.gender-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.gender-item {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.gender-icon {
  font-size: 20px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.gender-item.male .gender-icon {
  background-color: #e3f2fd;
}

.gender-item.female .gender-icon {
  background-color: #fce4ec;
}

.gender-info {
  flex: 1;
}

.gender-number {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.gender-percentage {
  font-size: 14px;
  color: #666;
}

.gender-chart {
  margin-top: 10px;
}

.gender-bar {
  height: 20px;
  border-radius: 10px;
  overflow: hidden;
  display: flex;
}

.male-bar {
  background-color: #2196F3;
  height: 100%;
  transition: width 0.3s;
}

.female-bar {
  background-color: #E91E63;
  height: 100%;
  transition: width 0.3s;
}

/* 世代分布 */
.generation-stats {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.generation-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.generation-label {
  min-width: 60px;
  font-weight: bold;
  color: #333;
}

.generation-bar-container {
  flex: 1;
  position: relative;
  height: 20px;
  background-color: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
}

.generation-bar {
  height: 100%;
  background-color: #4CAF50;
  transition: width 0.3s;
}

.generation-count {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  color: #333;
  font-weight: bold;
}

/* 年龄分布 */
.age-stats {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.age-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.age-label {
  min-width: 80px;
  font-weight: bold;
  color: #333;
}

.age-bar-container {
  flex: 1;
  position: relative;
  height: 20px;
  background-color: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
}

.age-bar {
  height: 100%;
  background-color: #FF9800;
  transition: width 0.3s;
}

.age-count {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  color: #333;
  font-weight: bold;
}

/* 关系类型分布 */
.relationship-stats {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.relationship-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.relationship-label {
  min-width: 80px;
  font-weight: bold;
  color: #333;
}

.relationship-bar-container {
  flex: 1;
  position: relative;
  height: 20px;
  background-color: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
}

.relationship-bar {
  height: 100%;
  background-color: #9C27B0;
  transition: width 0.3s;
}

.relationship-count {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  color: #333;
  font-weight: bold;
}

/* 教育程度分布 */
.education-stats {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.education-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.education-label {
  min-width: 80px;
  font-weight: bold;
  color: #333;
}

.education-bar-container {
  flex: 1;
  position: relative;
  height: 20px;
  background-color: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
}

.education-bar {
  height: 100%;
  background-color: #607D8B;
  transition: width 0.3s;
}

.education-count {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  color: #333;
  font-weight: bold;
}

/* 婚姻状态分布 */
.marital-stats {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.marital-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.marital-label {
  min-width: 80px;
  font-weight: bold;
  color: #333;
}

.marital-bar-container {
  flex: 1;
  position: relative;
  height: 20px;
  background-color: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
}

.marital-bar {
  height: 100%;
  background-color: #795548;
  transition: width 0.3s;
}

.marital-count {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  color: #333;
  font-weight: bold;
}

/* 最新动态 */
.recent-activities {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.activity-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #4CAF50;
}

.activity-icon {
  font-size: 16px;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
  border-radius: 50%;
}

.activity-content {
  flex: 1;
}

.activity-text {
  font-size: 14px;
  color: #333;
  margin-bottom: 2px;
}

.activity-time {
  font-size: 12px;
  color: #666;
}

@media (max-width: 768px) {
  .family-stats {
    padding: 15px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .gender-stats {
    flex-direction: column;
  }
  
  .generation-label,
  .age-label,
  .relationship-label,
  .education-label,
  .marital-label {
    min-width: 60px;
  }
}
</style> 